package intel;


import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description: 模拟客户端向服务器端发送一句话，服务器收到后打印控制台
 * 需要用到的技术点：
 * 1、网络编程
 * 2、客户端和服务器
 * 3、通过网络协议发送数据
 * @author: apple
 * @date:  2021/12/26 12:25 下午
 * @version 1.0
 **/
public class TCPTest {

    // 服务器端的端口
    static final int port = 8899;

    @Test
    public void client() throws IOException {
        // 服务器端的IP
        final InetAddress byName = InetAddress.getByName("127.0.0.1");

        Socket socket = new Socket(byName, port);
        System.out.println("服务器链接成功.....");
        OutputStream outputStream = socket.getOutputStream();
        // 字节流转换器,可以吧字符流转换为字节流
        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        // 服务器端发送消息
        writer.write("hello");
        System.out.println("发送消息成功....");
        writer.close();
        outputStream.close();
        socket.close();

    }

    @Test
    public void server() throws IOException {

        ServerSocket serverSocket = new ServerSocket(port);
        // 服务挂起，等待客户端发起请求，获取Socket对象（包含客户端各种信息）
        System.out.println("服务器挂起..........");
        Socket accept = serverSocket.accept();
        System.out.println("服务器收到了客户端请求.......");
        InputStream inputStream = accept.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffs = new byte[1024];
        int len;
        while (((len = inputStream.read(buffs)) != -1)) {
            outputStream.write(buffs,0, len);
        }

        String s = outputStream.toString();
        System.out.println(s);
        System.out.println("读取数据完毕.....");
        inputStream.close();
        accept.close();
        serverSocket.close();

    }
}
